

#include <iostream>
#include "eventmanager.h"
#include "log.h"

using namespace std;


EventManager::EventManager() {

};

//
//Returns the EventHandlersList associated to the event.
//Or NULL if the event id is not declared.
//
EventHandlersList* EventManager::_getEventHandlers(string eventIdentifier) {

    EventHandlersMap::iterator it;
    
    it = this->eventHandlers.find(eventIdentifier);

    //If the eventIdentifier is not already registered
    if(it == this->eventHandlers.end()){
        return NULL ;
    }
    else {
        return &(it->second);
    }

}

void EventManager::declareEvent(string eventIdentifier){

    EventHandlersList* ehList = this->_getEventHandlers(eventIdentifier);

    if(ehList == NULL){
        Log::Message("Declare event '"+eventIdentifier+"'.");
        this->eventHandlers[eventIdentifier] = *(new EventHandlersList());
    }
    else {
        Log::Warning("Event '"+eventIdentifier+"' already declared.");
    }

}

void EventManager::fireEvent(string eventIdentifier, EventHandlerData* ehData){
    Log::Message("Fire event "+eventIdentifier);

    EventHandlersList* eventHandlersToFire = this->_getEventHandlers(eventIdentifier);

    if(eventHandlersToFire != NULL) {

        for(EventHandlersList::iterator num = eventHandlersToFire->begin(); num != eventHandlersToFire->end(); ++num) {
           (*num)(*ehData);
        }
    } else {
        Log::Warning("Trying to fire unregistered event '" + eventIdentifier + "'.");
    }
}


void EventManager::registerEventHandler(string eventIdentifier, EventHandler eh) {

    EventHandlersList* ehList = this->_getEventHandlers(eventIdentifier);

    //If the event identifier is found
    if(ehList != NULL){
        ehList->push_back(eh);
        Log::Message("New event handler registered on event '" + eventIdentifier + "'.");

    } else {
        Log::Warning("Failed to register event handler on undeclared event '"+ eventIdentifier +"'.");
    }

    return;
}

